<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="问题" prop="questionName">
        <el-input
          v-model="queryParams.questionName"
          placeholder="请输入问题"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['system:question:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-check"
          @click="saveSoft"
          size="mini"
        >保存排序</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-upload2"
          @click="openExcel"
          size="mini"
        >导入题库</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>
    <el-table v-loading="loading" :data="questionList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="ID" align="center" prop="id" />
      <el-table-column label="问题" align="center" prop="questionName" />
      <el-table-column label="问题类型" align="center" prop="questionType" />
      <el-table-column label="选项A" align="center" prop="a" />
      <el-table-column label="选项B" align="center" prop="b" />
      <el-table-column label="选项C" align="center" prop="c" />
      <el-table-column label="选项D" align="center" prop="d" />
      <el-table-column label="选项E" align="center" prop="e" />
      <el-table-column label="选项F" align="center" prop="f" />
      <el-table-column label="选项答案" align="center" prop="answer" >
        <template slot-scope="scope">
          <div v-if="scope.row.questionType=='判断题'">
            <span v-if="scope.row.answer=='A'">正确</span>
            <span v-else>错误</span>
          </div>
          <div v-else>
            {{scope.row.answer}}
          </div>
        </template>
      </el-table-column>
      <el-table-column label="题目顺序" align="center" prop="sort" width="120">
        <template slot-scope="scope">
          <el-input-number v-model="scope.row.sort" placeholder="请输入题目顺序" style="width:110px;"></el-input-number>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['system:question:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:question:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 添加或修改题目对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body :close-on-click-modal="false">
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="问题类型" required prop="questionType" >
          <el-select v-model="form.questionType" placeholder="请选择问题类型" @change="changeType()">
            <el-option :label="value" :value="value" v-for="value in typeList"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="问题" prop="questionName" required>
          <el-input v-model="form.questionName" placeholder="请输入问题" />
        </el-form-item>
        <div v-if="form.questionType=='单选题'||form.questionType=='多选题'">
        <el-form-item label="选项A" prop="a">
          <el-input v-model="form.a" placeholder="请输入选项A" />
        </el-form-item>
        <el-form-item label="选项B" prop="b">
          <el-input v-model="form.b" placeholder="请输入选项B" />
        </el-form-item>
        <el-form-item label="选项C" prop="c">
          <el-input v-model="form.c" placeholder="请输入选项C" />
        </el-form-item>
        <el-form-item label="选项D" prop="d">
          <el-input v-model="form.d" placeholder="请输入选项D" />
        </el-form-item>
          <el-form-item label="选项E" prop="e">
            <el-input v-model="form.e" placeholder="请输入选项E" />
          </el-form-item>
          <el-form-item label="选项F" prop="f">
            <el-input v-model="form.f" placeholder="请输入选项F" />
          </el-form-item>
        </div>

        <el-form-item label="正确答案" prop="answer" required v-if="form.questionType=='单选题'">
          <el-select v-model="form.answer" placeholder="请选择答案" clearable>
            <el-option
              v-for="dict in dict.type.question_option"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="正确答案" prop="mutiOptions" required v-if="form.questionType=='多选题'">
          <el-checkbox-group v-model="form.mutiOptions" @change="checkedBoxChange" >
            <el-checkbox :label="dict.label" :key="dict.value" v-for="dict in dict.type.question_option" name="answer"></el-checkbox>
          </el-checkbox-group>
        </el-form-item>

        <el-form-item label="正确答案" prop="answer" required v-if="form.questionType=='判断题'">
          <el-select v-model="form.answer" placeholder="请选择答案" clearable>
            <el-option
              v-for="dict in dict.type.question_juage"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="填空答案" prop="answer" required v-if="form.questionType=='填空题'">
          <el-input v-model="form.answer" placeholder="请输入填空答案" />
        </el-form-item>
        <el-form-item label="题目顺序" prop="sort" required>
          <el-input-number v-model="form.sort" placeholder="请输入题目顺序"></el-input-number>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <el-dialog title="导入题库" :visible.sync="excel.open" width="500px" append-to-body>
      <el-upload
        ref="upload"
        :limit="1"
        accept=".xlsx, .xls"
        :headers="upload.headers"
        :action="upload.url + '?updateSupport=' + upload.updateSupport"
        :disabled="upload.isUploading"
        :on-progress="handleFileUploadProgress"
        :on-success="handleFileSuccess"
        :auto-upload="false"
        drag
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <div class="el-upload__tip text-center" slot="tip">
          <span>仅允许导入xls、xlsx格式文件。</span>
          <a href="/video/test.xlsx" style="font-size:12px;vertical-align: baseline;color:blue;">下载模板</a>
        </div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="importExcel">确 定</el-button>
        <el-button @click="excel.open = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listQuestion, getQuestion, delQuestion, addQuestion, updateQuestion } from "@/api/system/question";
import request from "@/utils/request";
import {getToken} from "@/utils/auth";

export default {
  name: "Question",
  dicts: ['question_option','question_juage'],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 题目表格数据
      questionList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        questionName: null,
        questionType: null,
      },
      // 表单参数
      form: {
      },
      // 表单校验
      rules: {
        questionType: [
          { required: true, message: '请选择问题类型', trigger: 'blur' }
        ],
        questionName: [
          { required: true, message: '请输入问题', trigger: 'blur' }
        ],
        answer: [
          { required: true, message: '请输入答案', trigger: 'blur' }
        ],
        a: [
          { required: true, message: '请输入选项A', trigger: 'blur' }
        ],
        b: [
          { required: true, message: '请输入选项B', trigger: 'blur' }
        ],
        c: [
          { required: true, message: '请输入选项C', trigger: 'blur' }
        ],
        d: [
          { required: true, message: '请输入选项D', trigger: 'blur' }
        ],
        mutiOptions: [
          { required: true, message: '请至少选择一个答案', trigger: 'change',type: 'array', }
        ],

      },
      typeList:{},
      excel:{
        open:false
      },
      upload: {
        // 是否显示弹出层（用户导入）
        open: false,
        // 弹出层标题（用户导入）
        title: "",
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的用户数据
        updateSupport: 0,
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/system/question/importData"
      },
    };
  },
  created() {
    this.getList();
    this.getTypeList();
  },
  methods: {
    changeType(){
      this.form.answer=null;
      this.form.mutiOptions=[];
      this.form.a=this.form.b=this.form.c=this.form.d=null;
    },
    checkedBoxChange(){
      this.$forceUpdate();
    },
    saveSoft(){
      let list=JSON.parse(JSON.stringify(this.questionList));
      let data=[];
      for(let i in list){
        data.push({id:list[i].id,sort:list[i].sort});
      }
      request({
        url:"/system/question/saveSoft",
        method:"PUT",
        data:data
      }).then(response=>{
        if(response.code==200){
          this.$message.success("保存成功");
          this.getList();
        }
      })
    },
    getTypeList(){
      request({
        url:"/system/question/typeList"
      }).then(response=>{
        this.typeList=response.data;
      })
    },
    /** 查询题目列表 */
    getList() {
      this.loading = true;
      listQuestion(this.queryParams).then(response => {
        this.questionList = response.data;
        // this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        questionName: null,
        questionType: null,
        a: null,
        b: null,
        c: null,
        d: null,
        answer: null,
        sort: null,
        createTime: null,
        updateTime: null,
        mutiOptions:[]
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加题目";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getQuestion(id).then(response => {
        this.form = response.data;
        this.form.mutiOptions=this.form.answer==null?[]:this.form.answer.split("");
        this.open = true;
        this.title = "修改题目";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if(this.form.questionType=='多选题'){
            this.form.answer=this.form.mutiOptions.join("");
          }
          if (this.form.id != null) {
            updateQuestion(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addQuestion(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除题目编号为"' + ids + '"的数据项？').then(function() {
        return delQuestion(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('system/question/export', {
        ...this.queryParams
      }, `question_${new Date().getTime()}.xlsx`)
    },
    openExcel(){
      this.excel.open=true;
    },
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true;
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      this.upload.open = false;
      this.upload.isUploading = false;
      this.$refs.upload.clearFiles();
      this.$alert("<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" + response.msg + "</div>", "导入结果", { dangerouslyUseHTMLString: true });
      this.getList();
    },
    // 提交上传文件
    importExcel() {
      this.$refs.upload.submit();
    }
  }
};
</script>
